package io.github.frailty9.crserver.config

import cn.dev33.satoken.exception.NotLoginException
import cn.dev33.satoken.exception.NotPermissionException
import cn.dev33.satoken.exception.NotRoleException
import cn.dev33.satoken.exception.SaTokenException
import cn.dev33.satoken.util.SaResult
import mu.KotlinLogging
import org.noear.solon.annotation.Component
import org.noear.solon.core.handle.Context
import org.noear.solon.core.handle.Filter
import org.noear.solon.core.handle.FilterChain

@Component
class AppFilter : Filter {
    val log = KotlinLogging.logger { }

    override fun doFilter(ctx: Context, chain: FilterChain) {
        try {
            log.debug { ctx.path() }
            chain.doFilter(ctx);
        } catch (e: SaTokenException) {
            when (e) {
                is NotLoginException -> {
                    log.error("NotLoginException on ${ctx.path()}: ${e.message}")
                    ctx.render(SaResult(401, "未登录", null))
                }
                is NotPermissionException -> {
                    log.error("NotPermissionException on ${ctx.path()}: ${e.message}")
                    ctx.render(SaResult(403, "没有权限", null))
                }
                is NotRoleException -> {
                    log.error("NotRoleException on ${ctx.path()}: ${e.message}")
                    ctx.render(SaResult(403, "权限不足", null))
                }
             }
        }
        catch (e: Throwable) {
            renderDefaultError(ctx, e)
        }
    }

    private fun renderDefaultError(ctx: Context, e: Throwable) {
        e.printStackTrace()
        log.error("RouterInterceptor error: ${e.message}")
        ctx.render(SaResult(500, "服务异常，请与管理员联系", null))
    }
}